#include "common.hpp"

int main()
{
    //socket创建
    Socket* serv_sock=new Socket();
    
    serv_sock->Bind();
    
    serv_sock->Listen();
    //EPOll创建
    Epoll* servEp=new Epoll();
    servEp->addFd(serv_sock->GetFd(),EPOLLIN|EPOLLET);
    //触发判断
    while(true)
    {
        int nfds=servEp->size();
        for(int i=0;i<nfds;i++)
        {
            int fd=servEp->triggerFd(i);
            //如果等于绑定的sockfd,则有客户端连接
            if(fd==serv_sock->GetFd())
            {
                int cli_fd=serv_sock->Accept();
                servEp->addFd(cli_fd,EPOLLIN|EPOLLET);
            }
            else if(servEp->triggerThing(i) & EPOLLIN)
            {
                while(true)
                {
                    char buff[BUFFER_NUM];
                    bzero(buff,sizeof(buff));
                    int read_bytes=read(fd,buff,sizeof(buff));
                    if(read_bytes>0)
                    {
                        printf("the message from client is:%s\n",buff);
                        write(fd,buff,sizeof(buff));
                    }
                    else if(read_bytes==-1&&(errno==EINTR))
                    {
                        printf("normal interrupt, once again...\n");
                        continue;
                    }
                    else if(read_bytes==-1&&(errno==EAGAIN||errno==EWOULDBLOCK))
                    {
                        printf("finished read\n");
                        break;
                    }
                    else
                    {
                        //read_bytes=0
                        printf("EOF,the client fd %d already disconnected\n",fd);
                        close(fd);
                        break;
                    }
                }
            }
            else{}
        }
    }
    return 0;
}
